#include "SoftwareSPI.h"

SoftwareSPI::SoftwareSPI( uint8_t pin_mosi, uint8_t pin_miso, uint8_t pin_sck,uint8_t pin_cs, uint8_t cpha, uint8_t cpol)
{
    _pin_sck = pin_sck;
    _pin_mosi = pin_mosi;
    _pin_miso = pin_miso;
    _pin_cs = pin_cs;
    _cpha = cpha;
    _cpol = cpol;
}

void SoftwareSPI::begin(uint8_t pin_cs)
{
    deselect();
    pinMode(_pin_cs, OUTPUT);

    pinMode(_pin_sck, OUTPUT);
    pinMode(_pin_mosi, OUTPUT);
    pinMode(_pin_miso, INPUT);
}

uint8_t SoftwareSPI::transfer(uint8_t b)
{
    uint8_t rec = 0;

    for (int i = 0; i < 8; i++)
    {
        if (!_cpha)
            digitalWrite(_pin_mosi, bitRead(b, 7 - i)); //MSB first
        digitalWrite(_pin_sck, !_cpol);
        if (_cpha)
            digitalWrite(_pin_mosi, bitRead(b, 7 - i));
        if (_cpha)
            bitWrite(rec, 7 - i, digitalRead(_pin_miso));
        digitalWrite(_pin_sck, _cpol);
    }

    return rec;
}

void SoftwareSPI::select()
{
    digitalWrite(_pin_cs, LOW);
}

void SoftwareSPI::deselect()
{
    digitalWrite(_pin_cs, HIGH);
}
